const os = require('node:os');
const { Worker, MessageChannel } = require('node:worker_threads');

const poolSize = os.cpus().length;

const workers = [];
const tunnels = [];

// 根据 cpu 核心数循环创建 8 个 Worker，id 为 index，也就是 0 到 7。
for (let i = 0; i < poolSize; i++) {
    const { port1, port2 } = new MessageChannel();
    const worker = new Worker('./pool-worker.cjs');
    worker.postMessage(
        { 
            type: 'startup', 
            id: i,
            channel: port2 
        },
      [port2],
    );
    // 把 Worker 实例和通信用的 port 放到数组里。
    tunnels.push(port1);
    workers.push(worker);
}

// 循环监听所有 port 的消息，打印下计算结果。
for (let i = 0; i < tunnels.length; i ++) {
    tunnels[i].on('message', (msg) => {
        console.log(`线程 ${msg.id} 计算出了结果 ${msg.res}`);
    })
}

let curIndex = 0;

// 然后封装一个 addJob 方法来发消息，从 0 到 7 依次调用工作线程来处理
function addJob(num) {
    const tunnel = tunnels[curIndex];
    tunnel.postMessage({ 
        value: num
    });
    curIndex = curIndex >= workers.length - 1 ? 0 : curIndex + 1;
}

for(let i = 0; i< 100; i++) {
    addJob(Math.floor(Math.random() * 1000000));
}